package com.faith.timefloating.network;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.faith.timefloating.model.Event;
import com.faith.timefloating.model.Feed;

import de.greenrobot.event.EventBus;

public class NetOperator {
	public static final String TAG = "NetOperator";
	private EventBus eventBus;
	private AQuery aq;
	private Context context;
	private static NetOperator instance;
	public static NetOperator getInstance(){
		if(instance == null){
			instance = new NetOperator();
		}
		return instance;
	}
	public NetOperator init(Context context){
		this.context = context;
		aq = new AQuery(context);
		eventBus = EventBus.getDefault();
		return instance;
	}
	public void getFBLinkFeedList(){
		String url = "https://graph.facebook.com/fql?access_token=102855336572948|AryFABd037nfBABEYBhWrdEX6LM&q=";
		String params = "SELECT post_id,message FROM stream WHERE source_id ='359264297468414' and actor_id = 359264297468414 LIMIT 3000";
		Map<String, String> param = new HashMap<String, String>();
		param.put("access_token", "102855336572948|AryFABd037nfBABEYBhWrdEX6LM");
		String endpoint = "";
		try {
			endpoint = url + URLEncoder.encode(params, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		aq.ajax(endpoint, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus ajaxStatus) {
                if(json != null){
                	try {
                		JSONArray array = json.getJSONArray("data");
    					JSONObject obj;
    					Feed item = null;
    					JSONObject likeObj;
    					JSONObject commentsObj;
    					ArrayList<Feed> feeds = new ArrayList<Feed>();
    					if(array.length() > 0){
    						for(int i = 0; i < array.length(); i++){
    							obj = array.getJSONObject(i);
    							item = new Feed();
    							item.setId(obj.getString("post_id"));
    							item.setContent(obj.getString("message"));
    							if(!TextUtils.isEmpty(item.getContent())){
    								feeds.add(item);
    							}
    						}
    					}
    					eventBus.post(new Event.GetFeedSuccess(feeds));
					} catch (JSONException e) {
						e.printStackTrace();
						eventBus.post(new Event.FailResponse());
					}
                } else {
                	Log.e(TAG, "Error: " + ajaxStatus.getCode());
                	eventBus.post(new Event.FailResponse());
                }
            }
		});
	}
}
